/**
 * Created by zhuo on 2017/4/10.
 */
var global_essays =
    [{
        id: 0,
        title: "Now Loading...",
    }, {
        id: 1,
        title: "如果该页面迟迟不刷新",
    }, {
        id: 2,
        title: "可能是数据库宕机了",
    }, {
        id: 3,
        title: "请通知博主尽快修复",
    }]

function blogClick() {
    listBlogs()
    asyncGlobalBlogs()
}

function essayClick() {
    listEssays()
    asyncGlobalEssays()
}

function asyncGlobalBlogs() {
    $.post('/getAllBlogs', function (data) {
        // console.log('Accepted data! : '+data)
        global_essays.splice(0, global_essays.length)
        $.merge(global_essays, data)
        // console.log('change data! : '+global_essays)
    }, "json")
}

function asyncGlobalEssays() {
    $.post('/getAllEssays', function (data) {
        // console.log('Accepted data! : '+data)
        global_essays.splice(0, global_essays.length)
        $.merge(global_essays, data)
        // console.log('change data! : '+global_essays)
    }, "json")
}

function listEssays() {
    createComponentContainer()
    vueGo()
}

function listBlogs() {
    createComponentContainer()
    blogVueGo()
}

function blogVueGo() {
    Vue.component('essay-component',{
        template: '#blog-list-template',
        data : function () {
            return {blogs : global_essays}
        },
        methods : {
            fillBlog : fill_blog
        }
    })

    new Vue({
        el : '#my-content'
    })
}

function createComponentContainer() {
    $('#my-content').html('<essay-component></essay-component>')
}

function vueGo() {
    Vue.component('essay-component', {
        template: '#essay-template',
        data: function () {
            return {essays: global_essays}
        },
        methods: {
            fillEssay: fill_essay
        }
    })
    new Vue({
        el: '#my-content'
    })
}

var vue_essay = {
    title: 'Loading...',
    content: '迟迟不刷新，怕是数据库宕机了<br/>数据库：这锅我来背'
}

function fill_essay(id) {
    putEssayContain()
    ajaxEssay(id)
}

function fill_blog(id) {
    putEssayContain()
    ajaxBlog(id)
}

function ajaxBlog(id) {
    $.post('/getBlogById', {id: id}, function (data) {
        vue_essay.title = data.title
        vue_essay.content = data.content
        console.log('get essay OK ! : ' + data)
    }, "json")
}

function ajaxEssay(id) {
    $.post('/getEssayById', {id: id}, function (data) {
        vue_essay.title = data.title
        vue_essay.content = data.content
        console.log('get essay OK ! : ' + data)
    }, "json")
}

function putEssayContain() {
    $('#my-content').html('<blog-show-component></blog-show-component>')


    Vue.component('blog-show-component', {
        template: '#blog-show-template',
        data: function () {
            return {
                blog: vue_essay
            }
        }
    })

    new Vue({
        el: '#my-content'
    })
}
